<template>
  <view class="user">
    <view class="user-header">
      <view class="user-info row-between">
        <view class="info row">
          <view v-if="isLogin">
            <image
                class="avatar mr20 flexnone"
                :src="getAvatarUrl(userInfo.avatar) || '/static/images/user/default_avatar.png'"
            ></image>
          </view>
          <view v-else>
            <image
                class="avatar mr20 flexnone"
                src="/static/images/user/default_avatar.png"
            />
          </view>
          <view class="white mr20" v-if="isLogin">
            <view class="name xxl line1">{{ userInfo.nickname }}
              <text class="tag">{{ userInfo.type_name }}</text>
            </view>
            <view class="tel"> {{ userInfo.mobile }}</view>
          </view>
          <view class="white" v-else @tap="goLogin">
            <view style="font-size: 42rpx; color: #ffffff">点击登录</view>
          </view>
        </view>
        <view class="row" style="align-self: flex-start">
          <view class="user-opt" @tap="goPage('/pages/user_set/user_set')">
            <image
                style="width: 58rpx; height: 58rpx"
                src="/static/images/icon_edit.png"
            ></image>
          </view>
        </view>
      </view>
    </view>
    <view class="order-nav bg-white">
      <view class="title row-between" @tap="goOrderPage('/pages/order/order')">
        <view class="lg" style="font-size: 28rpx; font-weight: bold">我的订单</view>
        <view class="muted sm row">
          全部
          <image class="icon-sm ml10" src="/static/images/arrow_right.png"></image>
        </view>
      </view>
      <view class="nav row">
        <view v-if="userInfo?.type_id != 2"
              class="item column-center mb20"
              @tap="goOrderPage('/pages/order/order',0)"
        >
          <view class="icon-contain">
            <view v-if="userInfo?.wait_confirm_count" class="badge xs row-center bg-white">
              {{ userInfo?.wait_confirm_count }}
            </view>
            <image class="nav-icon" src="/static/images/icon_daishangmen.png"></image>
          </view>
          <view class="sm mt10">待上门</view>
        </view>
        <view
            class="item column-center mb20"
            @tap="goOrderPage('/pages/order/order',1)"
        >
          <view class="icon-contain">
            <view
                v-if="userInfo?.confirm_count"
                class="badge xs row-center bg-white"
            >
              {{ userInfo?.confirm_count }}
            </view>
            <image class="nav-icon" src="/static/images/icon_my_huishou.png"></image>
          </view>
          <view class="sm mt10">回收中</view>
        </view>
        <view
            class="item column-center mb20"
            @tap="goOrderPage('/pages/order/order',2)"
        >
          <view class="icon-contain">
            <view
                v-if="userInfo?.complete_count"
                class="badge xs row-center bg-white"
            >
              {{ userInfo?.complete_count }}
            </view>
            <image class="nav-icon" src="/static/images/icon_my_wancheng.png"></image>
          </view>
          <view class="sm mt10">已完成</view>
        </view>
      </view>
      <view class="my-assets mt-5">
        <view class="my-item ml20 mr20 bt-line" @tap="requestSubscription"  v-if="isLogin && userInfo?.type_id == 2">
          <view class="nav row-between">
            <view class="row items-center">
              <u-icon name="chat" size="50" class="ml20 mr-1"></u-icon>
              <!--              <image class="icon-md ml20 mr-1" src="/static/images/subscription.png"></image>-->
              <view
                  :class="['subscription-status', subscriptionStatus ? 'subscribed' : 'not-subscribed']"

              >
                订阅消息
                <text class="subscription_status">{{ subscriptionStatus ? '已订阅' : '未订阅' }}</text>
              </view>
            </view>
            <view class="mr20">
              <image class="icon-sm" src="/static/images/arrow_right.png"></image>
            </view>
          </view>
        </view>
        <view class="my-item ml20 mr20 bt-line" @tap="goPage('/pages/as_us/as_us')">
          <view class="nav row-between">
            <view class="">
              <image class="icon-md ml20 mr-1" src="/static/images/about.png"></image>
              关于我们
            </view>
            <view class="mr20">
              <image class="icon-sm" src="/static/images/arrow_right.png"></image>
            </view>
          </view>
        </view>
        <view class="my-item mt-px ml20 mr20" @tap="goPage('/pages/feedback/feedback')">
          <view class="nav row-between">
            <view>
              <image
                  class="icon-md ml20 mr-1"
                  src="/static/images/yijian.png"
              ></image>
              意见反馈
            </view>
            <view class="mr20">
              <image class="icon-sm" src="/static/images/arrow_right.png"></image>
            </view>
          </view>
        </view>
        <view class="my-item mt-px ml20 mr20" @tap="goPage('/pages/customer_service/customer_service')">
          <view class="nav row-between">
            <view>
              <image class="icon-md ml20 mr-1" src="/static/images/kefu.png"></image>
              联系客服
            </view>
            <view class="mr20">
              <image class="icon-sm" src="/static/images/arrow_right.png"></image>
            </view>
          </view>
        </view>

      </view>
    </view>
    <tabbar/>
  </view>
</template>

<script setup lang="ts">
import {useUserStore} from '@/stores/user'
import {onShow} from '@dcloudio/uni-app'
import {storeToRefs} from 'pinia'
import {ref, onMounted, reactive} from 'vue'
import {useAppStore} from "@/stores/app";

const subscriptionStatus = ref(false)
const {getImageUrl} = useAppStore();
// 创建一个计算属性来处理头像URL
const getAvatarUrl = (avatar: string) => {
  console.log('getAvatarUrl', avatar)
  // 判断头像URL是否包含http或https
  if (avatar && !avatar.startsWith('http://') && !avatar.startsWith('https://')) {
    // 如果不包含协议，则使用配置的域名拼接
    return getImageUrl(avatar)
  }
  // 如果已经包含协议，则直接返回
  return avatar
}
// 增强版订阅状态检查 - 检查模板的实际订阅状态
const checkSubscriptionStatusEnhanced = () => {
  if (userStore?.userInfo?.type_id !== 2) {
    return;
  }
  try {

      const templateId = '5postuF8dMqMst9eJwDxL4vWudhMP4H4G8f1XWFXvQw'
      const hasSubscribed = uni.getStorageSync('subscription_status')
      // #ifdef MP-WEIXIN
      if (typeof wx !== 'undefined' && typeof wx.getSetting === 'function') {
        wx.getSetting({
          withSubscriptions: true,
          success: (res) => {
            try {
              console.log('getSetting:', res)
              // 检查主开关状态
              const mainSwitch = res?.subscriptionsSetting?.mainSwitch
              if (mainSwitch != true) {
                showSubscriptionSettingModal()
              }
              console.log('主开关状态:', mainSwitch)
              console.log('模板订阅状态:', res.subscriptionsSetting)

              // 检查用户是否已经订阅了指定模板
              if (res.subscriptionsSetting &&
                  res.subscriptionsSetting.itemSettings &&
                  res.subscriptionsSetting.itemSettings[templateId]) {

                // 模板订阅状态存在
                const status = res.subscriptionsSetting.itemSettings[templateId]
                console.log('模板订阅状态:', status)
                if (status === 'accept' || status == 'acceptWithForcePush') {
                  // 确认订阅，保持状态为true
                  subscriptionStatus.value = true
                } else {
                  console.log('未订阅或拒绝')
                  // 未订阅或拒绝，更新状态并清除本地存储
                  uni.showModal({
                    title: '消息订阅',
                    content: '为了及时收到订单状态更新，请订阅消息通知',
                    confirmText: '立即订阅',
                    cancelText: '稍后再说',
                    success: function(modalRes) {
                      if (modalRes.confirm) {
                        // 调用订阅函数
                        requestSubscription();
                      } else {
                        // 用户选择稍后再说，保持当前状态或使用本地存储状态
                        subscriptionStatus.value = !!hasSubscribed;
                      }
                    }
                  });
                }
              }
            } catch (parseError) {
              console.error('解析订阅设置时出错:', parseError)
              subscriptionStatus.value = !!hasSubscribed
            }
          },
          fail: (err) => {
            console.log('检查订阅设置失败，使用本地存储状态:', err)
            // 出错时保持本地存储的状态
            subscriptionStatus.value = !!hasSubscribed
          }
        })
      } else {
        // 基础库版本不支持，使用本地存储状态
        console.log('基础库版本不支持，使用本地存储状态')
        subscriptionStatus.value = !!hasSubscribed
      }
      // #endif

      // #ifndef MP-WEIXIN
      // 非微信小程序环境，直接使用本地存储状态
      subscriptionStatus.value = !!hasSubscribed
      // #endif
  } catch (error) {
    console.error('检查订阅状态时出错:', error)
    // 出现任何错误时，回退到本地存储状态
    const hasSubscribed = uni.getStorageSync('subscription_status')
    subscriptionStatus.value = !!hasSubscribed
  }
}

const state = reactive<{
  meta: any[]
  pages: any[]
}>({
  meta: [],
  pages: []
})


const userStore = useUserStore()
const {userInfo, isLogin} = storeToRefs(userStore)

const getData = async () => {

}
onShow(() => {
  userStore.getUser()
  checkSubscriptionStatusEnhanced()
})
onMounted(() => {
  checkSubscriptionStatusEnhanced()
})
const goLogin = () => {
  uni.navigateTo({
    url: '/pages/login/login'
  })
}

const goPage = (url: string) => {
  uni.navigateTo({
    url: url
  })
}

const app = getApp();

const goOrderPage = (url: string, params?: number) => {
  console.log(params)
  // 如果传入了参数，则存储参数；否则清除参数
  if (params !== undefined) {
    uni.setStorageSync('orderPageParams', {type: params});
  } else {
    console.log('清除参数');
    // 点击"全部"时清除存储的参数
    uni.removeStorageSync('orderPageParams');
  }
  uni.switchTab({
    url: url
  })
}
// 添加订阅消息功能
const requestSubscription = () => {
  // 检查用户是否为回收师傅
  if (userStore?.userInfo?.type_id !== 2) {
    return;
  }
  if (subscriptionStatus.value) {
    // 已订阅状态，提供取消订阅选项
    uni.showModal({
      title: '取消订阅',
      content: '您已订阅消息通知，如需取消请在微信设置中操作',
      confirmText: '去设置',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 打开微信设置页面
          if (typeof wx !== 'undefined' && typeof wx.openSetting === 'function') {
            wx.openSetting({
              withSubscriptions: true,
              success: (settingRes) => {
                console.log('打开设置成功', settingRes)
                // 重新检查订阅状态
                checkSubscriptionStatusEnhanced()
              },
              fail: (error) => {
                console.error('打开设置失败', error)
              }
            })
          }
        }
      }
    })
  } else {
    // 未订阅状态，请求用户确认后再订阅
    uni.showModal({
      title: '消息订阅',
      content: '订阅后可及时收到订单状态更新通知，是否确认订阅？',
      confirmText: '确认订阅',
      cancelText: '暂不订阅',
      success: (modalRes) => {
        if (modalRes.confirm) {
          // 用户确认后执行实际订阅
          performSubscription();
        } else {
          console.log('用户取消订阅');
        }
      }
    });
  }
}
// 实际执行订阅操作
const performSubscription = () => {
  const templateId = '5postuF8dMqMst9eJwDxL4vWudhMP4H4G8f1XWFXvQw';

  // 检查主开关状态
  if (typeof wx !== 'undefined' && typeof wx.getSetting === 'function') {
    wx.getSetting({
      withSubscriptions: true,
      success: (res) => {
        const mainSwitch = res?.subscriptionsSetting?.mainSwitch;
        if (mainSwitch != true) {
          // 主开关未开启，引导用户开启
          showSubscriptionSettingModal();
        } else {
          // 主开关已开启，执行订阅
          executeSubscribeMessage(templateId);
        }
      },
      fail: () => {
        // 检查失败时仍然尝试订阅
        executeSubscribeMessage(templateId);
      }
    });
  } else {
    executeSubscribeMessage(templateId);
  }
}

const showSubscriptionSettingModal = () => {
  uni.showModal({
    title: '消息订阅设置',
    content: '您需要在设置中开启消息订阅权限才能接收订单状态更新通知',
    confirmText: '去设置',
    cancelText: '稍后再说',
    success: (res) => {
      if (res.confirm) {
        // 用户点击去设置
        if (typeof wx !== 'undefined' && typeof wx.openSetting === 'function') {
          wx.openSetting({
            withSubscriptions: true,
            success: (settingRes) => {
              console.log('打开设置成功', settingRes);
              // 重新检查订阅状态
              checkSubscriptionStatusEnhanced();
            },
            fail: (error) => {
              console.error('打开设置失败', error);
            }
          });
        }
      }
    }
  });
};

// 执行订阅消息
const executeSubscribeMessage = (templateId) => {
  uni.requestSubscribeMessage({
    tmplIds: [templateId],
    success: (res) => {
      if (res[templateId] === 'accept' || res[templateId] === 'acceptWithForcePush') {
        // 订阅成功
        uni.showToast({
          title: '订阅成功',
          icon: 'success'
        });
        uni.setStorageSync('subscription_status', true);
        subscriptionStatus.value = true;
      } else if (res[templateId] === 'reject') {
        // 用户拒绝订阅
        uni.showModal({
          title: '订阅提醒',
          content: '您拒绝了订阅消息通知，如需接收订单状态更新，请在设置中开启消息订阅',
          confirmText: '去设置',
          cancelText: '稍后再说',
          success: (modalRes) => {
            if (modalRes.confirm) {
              if (typeof wx !== 'undefined' && typeof wx.openSetting === 'function') {
                wx.openSetting({
                  withSubscriptions: true,
                  success: (settingRes) => {
                    console.log('打开设置成功', settingRes);
                    checkSubscriptionStatusEnhanced();
                  },
                  fail: (error) => {
                    console.error('打开设置失败', error);
                  }
                });
              }
            }
          }
        });
        subscriptionStatus.value = false;
        uni.removeStorageSync('subscription_status');
      }
    },
    fail: (err) => {
      console.error('订阅消息失败:', err);
      // 不显示错误提示给用户，除非是重要错误
      if (err.errMsg && !err.errMsg.includes('fail cancel') && !err.errMsg.includes('last call has not ended')) {
        uni.showModal({
          title: '订阅提醒',
          content: '订阅消息失败，您可以前往设置中手动开启消息订阅',
          confirmText: '去设置',
          cancelText: '稍后再说',
          success: (modalRes) => {
            if (modalRes.confirm) {
              if (typeof wx !== 'undefined' && typeof wx.openSetting === 'function') {
                wx.openSetting({
                  withSubscriptions: true,
                  success: (settingRes) => {
                    console.log('打开设置成功', settingRes);
                    checkSubscriptionStatusEnhanced();
                  },
                  fail: (error) => {
                    console.error('打开设置失败', error);
                  }
                });
              }
            }
          }
        });
      }
      subscriptionStatus.value = false;
      uni.removeStorageSync('subscription_status');
    }
  });
}
getData()
</script>

<style lang="scss" scoped>
.user {
  background-color: #f8f8f8;
}

.user-header {
  padding: 150rpx 0;

  background-color: #236af6;
}

.user-info {
  padding: 0 30rpx;

  .avatar {
    height: 140rpx;
    width: 140rpx;
    border-radius: 50%;
    overflow: hidden;
  }

  .name {
    text-align: left;
    margin-bottom: 5rpx;
    max-width: 400rpx;
  }

  .user-opt {
    position: relative;
    margin-top: 40rpx;
  }
}

.order-nav {
  .icon-contain {
    position: relative;
  }
}

.order-nav {
  margin: -120rpx 20rpx 0;
  border-radius: 16rpx;
}

.server-nav {
  margin: 20rpx;
  border-radius: 8rpx;
}

.title {
  height: 88rpx;
  padding: 0 30rpx;
}

.nav {
  padding: 26rpx 0 0;

  .assets-item {
    flex: 1;
    border-radius: 8rpx;
  }

  .item {
    width: 33.33%;
    height: 120rpx;
  }

  .badge {
    padding: 0 6rpx;
    min-width: 28rpx;
    height: 28rpx;
    border-radius: 28rpx;
    box-sizing: border-box;
    border: 1rpx solid;
    position: absolute;
    left: 33rpx;
    top: -10rpx;
    z-index: 2;
  }

  .nav-icon {
    width: 52rpx;
    height: 52rpx;
  }

  .item_card {
    height: 120rpx;
  }
}

.my-item {
  height: 100rpx;
}

.tag {
  margin-left: 10rpx;
  padding: 0 10rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #f8f8f8;
  border-radius: 16rpx;
}

.subscription_status {
  border: 1rpx solid;
  border-radius: 16rpx;
  padding: 0 10rpx;
  font-size: 28rpx;
  background-color: #f8f8f8;
  margin-left: 10rpx;
}
</style>